#pragma once
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;
#define FIFO_FILE "fifo"
#define PATH "."
struct NAMEFIFO
{
    public:
    NAMEFIFO(const string path, const string name)
        : _name(name), _path(path)
    {
        _fifoname = _path + "/" + _name;
        // 创建管道
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            cerr << "fifo open failed" << endl;
        }
        else
            cout << "mkfifo sucess" << endl;
    }
    ~NAMEFIFO()
    {
        int n = unlink(_fifoname.c_str());
        if (n < 0)
        {
            cerr << "fifo unlink failed" << endl;
        }
        else
        {
            cout << "fifo unlink success" << endl;
        }
    }

private:
    string _fifoname;
    string _path;
    string _name;
};
struct Fileopen
{
    public:
    Fileopen(const string path, const string name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }
    ~Fileopen() = default;
    void openForRead()
    {
         _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            cerr << "open fail" << endl;
        }
        cout << "open success" << endl;
    }
    void openForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            cerr << "open fail" << endl;
        }
        cout << "open success" << endl;
    }
    void Write()
    {
        string message;
        int cnt = 1;
        pid_t id = getpid();
        while (true)
        {
            cout << "please enter$";
            getline(cin, message);
            message += (",message number :" + to_string(cnt++) + ", {" + to_string(id) + "}");
            write(_fd, message.c_str(), message.length());
        }
    }
    void Read()
    {
        while (true)
        {
            char buf[1024];
            int num = read(_fd, buf, sizeof(buf) - 1);
            if (num > 0)
            {
                buf[num] = 0;
                cout << "client say : " << buf << endl;
            }
            else if (num == 0)
            {
                cout << "client quit! me too!" << endl;
                break;
            }
            else
            {
                cerr << "read error" << endl;
                break;
            }
        }
    }
    void Close()
    {
       if(_fd>0)
       close(_fd);
    }
   
private:
    string _fifoname;
    string _path;
    string _name;
    int _fd;
};